package com.irdstudio.efp.nls.service.impl.yed.apply;

import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.constant.SDicToExternalConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.exception.OcmSystemException;
import com.irdstudio.basic.framework.core.util.sdic.SDicToExternal;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.ctr.service.facade.CtrLoanContService;
import com.irdstudio.efp.ctr.service.vo.CtrLoanContVO;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.facade.CusReferrerInfoService;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.cus.service.vo.CusReferrerInfoVO;
import com.irdstudio.efp.esb.service.bo.req.sed.repay.ReqLoanRepayResultQryBean;
import com.irdstudio.efp.esb.service.bo.resp.sed.repay.RespLoanRepayResultQryBean;
import com.irdstudio.efp.esb.service.bo.resp.yed.YedLoanReleaseReqBean;
import com.irdstudio.efp.esb.service.bo.resp.yed.YedLoanReleaseRespBean;
import com.irdstudio.efp.esb.service.facade.EsbInvokeWrapper;
import com.irdstudio.efp.esb.service.facade.yed.YedHjLoanReleaseService;
import com.irdstudio.efp.esb.service.facade.sed.repay.LoanRepayResultQryService;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.nls.common.constant.NlsApplyInfoEnums;
import com.irdstudio.efp.nls.common.constant.sed.SedNlsEnum;
import com.irdstudio.efp.nls.common.exception.LoanReleaseException;
import com.irdstudio.efp.nls.common.exception.LoanRepaySyncException;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.facade.NlsPublicService;
import com.irdstudio.efp.nls.service.facade.NlsQueueSoltComnService;
import com.irdstudio.efp.nls.service.facade.UpdateLmtPrdContService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.facade.yed.YedGjjLoanService;
import com.irdstudio.efp.nls.service.impl.yed.YedSoltServiceImpl;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.irdstudio.basic.framework.core.constant.SDicToExternalConstant.SYSID_IFP;
import static com.irdstudio.efp.console.common.ConsoleConstant.*;
import static com.irdstudio.efp.nls.common.constant.yed.YedCommonConstant.FLOW_STATUS_6;
import static com.irdstudio.efp.nls.common.constant.yed.YedCommonConstant.FLOW_STATUS_7;

/**
 * 需求编号：优e贷需求编号<br/>
 * 问题编号：<br/>
 * 功能描述：优e贷用信放款插槽<br/>
 * 开发人员：周才顺<br/>
 * 创建时间：2020/8/30 9:36
 *
 * @Author zhoucs1
 * @Version 1.0
 * @Since 1.0
 */
@Service("yedLoanReleaseService")
@Scope("prototype")
public class YedLoanReleaseServiceImpl extends YedSoltServiceImpl {
    /**
     * 日志信息
     */
    private final Logger logger = LoggerFactory.getLogger(YedLoanReleaseServiceImpl.class);

    /**
     * 一年判断
     */
    private static final String ONE_YEAR = "Y1";
    /**
     * 没有放款
     */
    private static final String NO_DATA = "0";

    private NlsApplyInfoVO nlsApplyInfoVO;

    public NlsApplyInfoVO getNlsApplyInfoVO() {
        return nlsApplyInfoVO;
    }

    public void setNlsApplyInfoVO(NlsApplyInfoVO nlsApplyInfoVO) {
        this.nlsApplyInfoVO = nlsApplyInfoVO;
    }

    @Override
    protected void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
        String applySeq = nlsApplyInfoVO.getApplySeq();
        logger.info("======>【优e贷放款服务】开始,流水号" + applySeq + "<======");
        // 获取合同信息
        CtrLoanContVO ctrLoanContVO = getCtrLoanContVO(nlsApplyInfoVO);
        Optional.ofNullable(ctrLoanContVO).orElseThrow(() -> new BizException("【优e贷放款插槽执行失败】 获取贷款合同为空!!!"));
        // 获取额度信息
        LmtPrdContVO lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(nlsApplyInfoVO.getLmtApplySeq());
        Optional.ofNullable(lmtPrdContVO).orElseThrow(() -> new BizException("【优e贷放款插槽执行失败】 获取额度为空!!!"));
        // 获取授信信息
        NlsCreditInfoVO nlsCreditInfoVO = nlsCreditInfoService.queryByLmtApplySeq(nlsApplyInfoVO.getLmtApplySeq());
        Optional.ofNullable(nlsCreditInfoVO).orElseThrow(() -> new BizException("【优e贷放款插槽执行失败】 获取授信信息为空!!!"));
        // 获取产品信息
        PrdInfoVO proInfo = nlsPublicService.getProInfo(nlsApplyInfoVO.getPrdId());
        Optional.ofNullable(proInfo).orElseThrow(() -> new BizException("【优e贷放款插槽执行失败】 获取产品为空!!!"));
        // 获取客户信息
        CusIndivVO cusIndivVO = new CusIndivVO();
        cusIndivVO.setCusId(nlsApplyInfoVO.getCusId());
        cusIndivVO = cusIndivService.queryByPk(cusIndivVO);
        Optional.ofNullable(cusIndivVO).orElseThrow(() -> new BizException("【优e贷放款插槽执行失败】 获取客户信息为空!!!"));

        /*###################################################################################################*/
        /****************************** 放款插槽插槽主流程 **************************************************/
        /*###################################################################################################*/
        // 放款开立查询接口
        try {
            YedLoanReleaseRespBean respLoanReleaseBean = null;
            // 放款查询
            RespLoanRepayResultQryBean respLoanRepayResultQryBean = getRespLoanRepayResultQryBean(nlsApplyInfoVO.getGlobalSerno());
            // 查询结果
            String qrySt = respLoanRepayResultQryBean.getQrySt();

            if (SedNlsEnum.QuerySts.WITHOUT.getValue().equals(qrySt)) { // 未放款 调用贷款开立接口
                // 调用互金贷款开立发放接口 并 插入表
                respLoanReleaseBean = callLoanRelease(nlsApplyInfoVO, ctrLoanContVO, proInfo, lmtPrdContVO, cusIndivVO, nlsCreditInfoVO);
                // 放款放款申请表状态为 通过
                updateLoanReleaseStatus(nlsApplyInfoVO, respLoanReleaseBean.getLoanNo(), respLoanReleaseBean.getDistrNo());
                // 更新额度有效期为一年
                updateLmtTerm(nlsApplyInfoVO);
                try {
                    yedSyncLoanInfoService.doExecute(nlsProcessBizVo, nlsApplyInfoVO);
                } catch (Exception e) {
                    logger.error("放款申请流水号【 " + nlsApplyInfoVO.getApplySeq() + "】，全局流水号【" + nlsApplyInfoVO.getGlobalSerno() + "】，成功还款后执行同步任务失败！");
                    throw new LoanRepaySyncException("放款后同步任务执行失败");
                }

            }
        } catch (LoanReleaseException e) {
            logger.error(Arrays.toString(e.getStackTrace()));
            setException(nlsProcessBizVo, e);
            logger.error("【优e贷放款流程未执行成功】 转为更新补偿任务处理!!!" + e);
        } catch (LoanRepaySyncException e) {
            logger.error(Arrays.toString(e.getStackTrace()));
            setException(nlsProcessBizVo, e);
            logger.error("【优e贷放款流程未执行成功】 转为同步任务处理!!!" + e);
        } catch (Exception e) {
            logger.error(Arrays.toString(e.getStackTrace()));
            // 设置放款状态
            nlsApplyInfoVO.setDnSts(BaseConstant.DN_STS_0);
            // 设置异常信息
            setException(nlsProcessBizVo, e);
            logger.error("【优e贷放款插槽执行失败】 遇到未知异常!!!" + e);
        } finally {
            //调用公积金回写接口
            yedGjjLoanService.callSyncGjjInvoteApply(nlsApplyInfoVO);

            logger.info("======>【优e贷放款服务】结束,流水号" + applySeq + "<======");
        }

    }


    /**
     * 设置异常信息: <br>
     * 0.1:caoxin:2019/6/24 18:53: 设置异常信息<br>
     *
     * @return
     * @author caoxin
     * @date 2019/6/24 18:53
     * @version 0.1
     * @since 2019/6/24 18:53
     */
    private void setException(NlsProcessBizVO nlsProcessBizVo, Exception e) {
        nlsProcessBizVo.setExceptionFlag(Boolean.TRUE);
        nlsProcessBizVo.setRefuseMsg(e.getMessage());
        nlsProcessBizVo.setExceptionMsg(e);
        setNlsProcessException(nlsProcessBizVo, e);
    }

    /**
     * 调用放款查询接口: <br>
     * <p>
     * 0.1:caoxin:2019/6/20 8:41: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/6/20 8:41
     * @version 0.1
     * @since 2019/6/20 8:41
     */

    public RespLoanRepayResultQryBean getRespLoanRepayResultQryBean(String globalSerno) throws ESBException, InterruptedException {
        ReqLoanRepayResultQryBean reqLoanRepayResultQryBean = new ReqLoanRepayResultQryBean();
        // 全局流水号 公共报文头的全局流水号
        reqLoanRepayResultQryBean.setTxnGlblSrlNo(globalSerno);

        EsbInvokeWrapper esbInvokeWrapper = new EsbInvokeWrapper(loanRepayResultQryService, reqLoanRepayResultQryBean, nlsQueueSoltComnService);
        RespLoanRepayResultQryBean respLoanRepayResultQryBean = (RespLoanRepayResultQryBean) esbInvokeWrapper.invoke3Threes();
        Objects.requireNonNull(respLoanRepayResultQryBean, "优e贷调用互联网金融平台放款查询返回对象为空!!!");
        return respLoanRepayResultQryBean;
    }

    /**
     * 获取合同: <br>
     * <p>
     * 0.1:caoxin:2019/6/20 8:39: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/6/20 8:39
     * @version 0.1
     * @since 2019/6/20 8:39
     */
    private CtrLoanContVO getCtrLoanContVO(NlsApplyInfoVO nlsApplyInfoVO) {
        // 获取合同信息
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        // 业务流水号-授信申请流水号
        ctrLoanContVO.setSerno(nlsApplyInfoVO.getApplySeq());
        // 合同类型，借款合同（两条数据是一样的）
        ctrLoanContVO.setContType(CONT_TYPE_02);
        ctrLoanContVO = ctrLoanContService.qryBySernoAndContTyp(ctrLoanContVO);
        return ctrLoanContVO;
    }

    /**
     * 设置异常信息: <br>
     * <p>
     * 0.1:caoxin:2019/6/1 11:59: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/6/1 11:59
     * @version 0.1
     * @since 2019/6/1 11:59
     */
    private void setNlsProcessException(NlsProcessBizVO nlsProcessBizVo, Exception e) {
        nlsProcessBizVo.setExceptionFlag(Boolean.TRUE);
        nlsProcessBizVo.setRefuseMsg(e.getMessage());
    }

    /**
     * 额度恢复 更新预占用额度和可用额度: <br>
     * <p>
     * 0.1:caoxin:2019/5/22 20:07: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/5/22 20:07
     * @version 0.1
     * @since 2019/5/22 20:07
     */

    public void recoverAmt(NlsApplyInfoVO nlsApplyInfoVO, LmtPrdContVO lmtPrdContVO) throws LoanReleaseException {
        // 通过授信申请流水号获取除了自身外的所有支用申请流水号集  还需要修改
        updateLmtPrdContService.recoverLmtPro(nlsApplyInfoVO.getLmtApplySeq(), nlsApplyInfoVO.getApplySeq());
    }

    /**
     * 更新额度信息: <br>
     * <p>
     * 0.1:caoxin:2019/5/22 19:48: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/5/22 19:48
     * @version 0.1
     * @since 2019/5/22 19:48
     */
    private void updateLmtAmt(NlsApplyInfoVO nlsApplyInfoVO, LmtPrdContVO lmtPrdContVO) throws OcmSystemException {
        // 通过授信申请流水号获取除了自身外的所有支用申请流水号集
        List<String> applySeqs = updateLmtPrdContService.getApplySeqList(nlsApplyInfoVO.getLmtApplySeq());
        // 获取已用额度
        BigDecimal occAmt = updateLmtPrdContService.getOccAmt(applySeqs);
        // 获取预占用额度
        BigDecimal preOccAmt = updateLmtPrdContService.getPreOccAmt(nlsApplyInfoVO.getLmtApplySeq());
        // 更新已用额度
        lmtPrdContVO.setOccAmt(occAmt.add(preOccAmt));
        // 更新预占用额度
        lmtPrdContVO.setPreOccAmt(BigDecimal.ZERO);
        // 更新可用额度
        lmtPrdContVO.setAvailAmt(lmtPrdContVO.getLmtAmt().subtract(occAmt.add(preOccAmt)));
        int result = 0;
        try {
            result = lmtPrdContService.updateByPk(lmtPrdContVO);
        } catch (Exception e) {
            throw new OcmSystemException("【优e贷】放款插槽 额度占用失败!!!");
        }
        if (result != 1) {
            throw new OcmSystemException("【优e贷】放款插槽 额度占用失败!!!");
        }
    }

    /**
     * 更新贷款状态: <br>
     * <p>
     * 0.1:caoxin:2019/5/22 17:17: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/5/22 17:17
     * @version 0.1
     * @since 2019/5/22 17:17
     */
    private void updateLoanReleaseStatus(NlsApplyInfoVO nlsApplyInfoVO, String loanNo, String distrNo) throws LoanReleaseException {
        String msg = "更新用信申请表 用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】更新 放款状态 贷款号 发放号,放款状态,放款金额失败!!!";
        // 更新用信申请放款状态为成功
        nlsApplyInfoVO.setDnSts(BaseConstant.DN_STS_6);
        // 更新用信申请放款金额为 用信申请金额
        final String amoutOfLoan = nlsApplyInfoVO.getApplyAmt().setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        nlsApplyInfoVO.setAmountOfLoan(amoutOfLoan);
        // 流程结束
        nlsApplyInfoVO.setFlowStatus(FLOW_STATUS_6);
        // 更新贷款号和发放号
        nlsApplyInfoVO.setLoanNo(loanNo);
        nlsApplyInfoVO.setDistrNo(distrNo);
        // 执行次数更新为0
        nlsApplyInfoVO.setExecuteTime(0);
        // 设置失败原因为空
        nlsApplyInfoVO.setRefuseCause(StringUtils.EMPTY);
        //用信申请状态
        nlsApplyInfoVO.setNlsApplyState(BaseConstant.NLS_APPLY_STATE_02);
        int result = 0;
        try {
            result = nlsApplyInfoService.updateByPk(nlsApplyInfoVO);
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(msg);
            }
            // 发送mq, 不更新放款状态,授信审批状态,该笔用信任然为处理中
            logger.error("用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】放款失败 执行放款补偿任务", e);
            throw new LoanReleaseException("用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】放款失败 执行放款补偿任务");
        }
        if (result != 1) {
            if (logger.isErrorEnabled()) {
                logger.error(msg);
            }
            // 发送mq, 不更新放款状态,授信审批状态,该笔用信任然为处理中
            logger.error("用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】放款失败 执行放款补偿任务");
            throw new LoanReleaseException("用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】放款失败 执行放款补偿任务");
        }
    }

    /**
     * 更新用信基本信息表: <br>
     * <p>
     * 0.1:caoxin:2019/5/22 15:46: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/5/22 15:46
     * @version 0.1
     * @since 2019/5/22 15:46
     */
    private void updateNlsApplyInfo(NlsApplyInfoVO nlsApplyInfoVO) throws LoanReleaseException {
        // 放款状态
        nlsApplyInfoVO.setDnSts(BaseConstant.DN_STS_0);
        // 网贷申请状态
        nlsApplyInfoVO.setNlsApplyState(NlsApplyInfoEnums.NlsApplyState.REJECT.getValue());
        // 流程状态
        nlsApplyInfoVO.setFlowStatus(FLOW_STATUS_7);
        int result = 0;
        try {
            result = nlsApplyInfoService.updateByPk(nlsApplyInfoVO);
        } catch (Exception e) {
            // throw new OcmSystemException("用信流水号【"+nlsApplyInfoVO.getApplySeq()+"】 【优e贷放款插槽执行失败】 更新用信申请表放款状态为放款成功失败!");
            // 发送mq, 不更新放款状态,授信审批状态,该笔用信任然为处理中
            throw new LoanReleaseException();
        }
        if (result != 1) {
            // throw new OcmSystemException("用信流水号【"+nlsApplyInfoVO.getApplySeq()+"】 更新用信申请表放款状态为放款成功失败!");
            // 发送mq, 不更新放款状态,授信审批状态,该笔用信任然为处理中
            throw new LoanReleaseException();
        }
    }

    /**
     * 调用互联网金融接口: <br>
     * <p>
     * 0.1:caoxin:2019/5/22 15:33: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/5/22 15:33
     * @version 0.1
     * @since 2019/5/22 15:33
     */
    private YedLoanReleaseRespBean callLoanRelease(NlsApplyInfoVO nlsApplyInfoVO, CtrLoanContVO ctrLoanContVO, PrdInfoVO proInfo, LmtPrdContVO lmtPrdContVO, CusIndivVO cusIndivVO, NlsCreditInfoVO nlsCreditInfoVO) throws OcmSystemException, LoanReleaseException {
        YedLoanReleaseReqBean reqLoanReleaseBean = new YedLoanReleaseReqBean();
        try {
            /*###################################################################################################*/
            /****************************** 获取放款拼装信息 ****************************************************/
            /*###################################################################################################*/
            // 来源用信申请信息表 客户号
            String cusId = cusIndivVO.getInnerCusId();

            // 来源用信申请信息表 币种 获取的值是 CNY  需要送的值是156
            String loanCcy = SDicToExternal.getExternalSysDicVal(SYSID_IFP, SDicToExternalConstant.CUR_TYPE, nlsApplyInfoVO.getLoanCcy());
            // 来源用信申请信息表 还款方式
            String repayMethod = SDicToExternal.getExternalSysDicVal(SYSID_IFP, SDicToExternalConstant.REPAY_MODE, nlsApplyInfoVO.getRepayMethod());
            // 来源用信申请信息表 执行利率送整数(贷款利率)
            BigDecimal rateY = nlsApplyInfoVO.getLoanRate().setScale(4, BigDecimal.ROUND_HALF_UP);
            // 来源用信申请信息表 nls_apply放款金额
            BigDecimal applyAmt = nlsApplyInfoVO.getApplyAmt().setScale(2, BigDecimal.ROUND_HALF_UP);
            // 来源用信申请信息表 期限
            String loanTerm = nlsApplyInfoVO.getLoanTerm();
            Objects.requireNonNull(loanTerm, "【优e贷放款插槽执行失败-获取放款信息失败】来源用信申请信息表 期限 为空!!!");
            // 来源用信申请信息表 期限类型 D,M,Y
            String loanTermType = nlsApplyInfoVO.getLoanTermType();
            Objects.requireNonNull(loanTermType, "【优e贷放款插槽执行失败-获取放款信息失败】来源用信申请信息表 期限类型 为空!!!");
            // 来源贷款合同表 取用信合同
            String contNo = ctrLoanContVO.getContNo();
            Objects.requireNonNull(contNo, "【优e贷放款插槽执行失败-获取放款信息失败】来源贷款合同表 取授信合同 为空!!!");
            // 来源产品信息表 还款周期
            String repaymentPeriod = nlsApplyInfoVO.getRepaymentPeriod();
            Objects.requireNonNull(repaymentPeriod, "【优e贷放款插槽执行失败-获取放款信息失败】来源额度信息表 还款周期 为空!!!");
            // 来源产品信息表 还款周期单位类型
            String repaymentDayType = nlsApplyInfoVO.getRepaymentPeriodType();
            Objects.requireNonNull(repaymentDayType, "【优e贷放款插槽执行失败-获取放款信息失败】来源额度信息表 还款周期单位类型 为空!!!");
            // 汇通达为0
            BigDecimal rateRadio = BigDecimal.ZERO;//nlsPublicService.getintRateRatio(nlsApplyInfoVO.getCertCode(), nlsApplyInfoVO.getCertType(), nlsApplyInfoVO.getLmtApplySeq());
            /*###################################################################################################*/
            /******************************拼装放款信息 **********************************************************/
            /*###################################################################################################*/
            // 互金客户编号
            reqLoanReleaseBean.setClntNo(cusId);
            // 互金产品编号 这个判断还是有风险的需要产品期限类型为Y
            String ifpProduct = "10003003";
            // 产品编号
            reqLoanReleaseBean.setProdType(ifpProduct);
            // 项目号
            reqLoanReleaseBean.setPrjNo(lmtPrdContVO.getLmtApplySeq());
            // 币种nlsstageinfoservice
            reqLoanReleaseBean.setCurrCd(loanCcy);
            // 贷款金额
            reqLoanReleaseBean.setContrAmt(applyAmt.doubleValue());
            // 还款方式
            reqLoanReleaseBean.setRpyMd(repayMethod);
            // 结息频率
            reqLoanReleaseBean.setIntSetlFrqcy(repaymentDayType.concat(repaymentPeriod));
            // 贷款期限
            reqLoanReleaseBean.setLoanTrm(loanTerm);
            // 期限类型
            reqLoanReleaseBean.setTrmType(loanTermType);
            // 还款日 固定
            reqLoanReleaseBean.setIntSetlDt(Objects.isNull(proInfo.getInteDay()) ? "21" : proInfo.getInteDay());
            // 正常利率
            reqLoanReleaseBean.setComIntRate(Optional.ofNullable(rateY).orElse(BigDecimal.ZERO).multiply(new BigDecimal("100")).doubleValue());
            // 正常利率浮动比
            reqLoanReleaseBean.setComIntRateFltIntPrt(Optional.ofNullable(rateRadio).orElse(BigDecimal.ZERO).multiply(new BigDecimal("100").setScale(2, BigDecimal.ROUND_HALF_UP)).doubleValue());
            // 合同号
            reqLoanReleaseBean.setCrdtContrNo(contNo);
            // 手机号
            reqLoanReleaseBean.setMblNo(nlsApplyInfoVO.getMobile());
            // 下一结息日期 互金要求赋值为空
            reqLoanReleaseBean.setNxtIntSetlDt(StringUtils.EMPTY);
            // 账户机构
            reqLoanReleaseBean.setTxnBrId(getRefferOrgId(nlsCreditInfoVO));
            //贷款期限12期以内送10003003，以上的送10003004
            reqLoanReleaseBean.setProdType(("3".equals(loanTerm)||"6".equals(loanTerm)||"12".equals(loanTerm))?"10003003":"10003004");
            /***********************************************************************************/
            // 数组 放款
            YedLoanReleaseReqBean.IntSetInfArry intSetInf1 = new YedLoanReleaseReqBean.IntSetInfArry();
            // 账户分类
            intSetInf1.setAcctCtgry(ACCOUNT_TYPE_I);
            // 金额类型
            intSetInf1.setAmtType(AMT_TYPE_PF);
            // 结算账户分类
            intSetInf1.setBlgAcctCl(ACCOUNT_TYPE_PAY);
            // 币种
            intSetInf1.setBlgAcctCurrCd(loanCcy);
            // 放款账户
            intSetInf1.setBlgAcctNo(nlsApplyInfoVO.getDnAccount());
            // 产品类型
            intSetInf1.setBlgAcctProdType(ifpProduct);
            // 结算方式
            intSetInf1.setBlgMth(PAYMENT_TYPE_R);
            // 受托支付行号
            intSetInf1.setBlgAcctBnkNo(nlsApplyInfoVO.getBankId());
            // 本行标志 1本行：2他行：3未知
            // 如果银行名称包含广州则为0 否则为1
            intSetInf1.setOwnOthrBankflg(Optional.ofNullable(nlsApplyInfoVO.getBankName()).orElse(StringUtils.EMPTY).contains("广州银行") ? "1" : "2");
            /***********************************************************************************/
            // 数组 扣款
            YedLoanReleaseReqBean.IntSetInfArry intSetInf2 = new YedLoanReleaseReqBean.IntSetInfArry();
            intSetInf2.setAcctCtgry(ACCOUNT_TYPE_I);
            intSetInf2.setAmtType(AMT_TYPE_PF);
            intSetInf2.setBlgAcctCl(ACCOUNT_TYPE_AUT);
            intSetInf2.setBlgAcctCurrCd(loanCcy);
            intSetInf2.setBlgAcctNo(nlsApplyInfoVO.getRecvAcctNo());
            intSetInf2.setBlgAcctProdType(ifpProduct);
            intSetInf2.setBlgMth(PAYMENT_TYPE_R);
            /***********************************************************************************/
            reqLoanReleaseBean.getIntSetInfArry().add(intSetInf1);
            reqLoanReleaseBean.getIntSetInfArry().add(intSetInf2);
        } catch (Exception e) {
            e.printStackTrace();
            throw new OcmSystemException("【优e贷放款插槽执行失败】调用开立发放系统转化值失败!异常信息为：" + e.getMessage());
        }
        // 请求放款
        NlsApplyInfoVO nlsApplyInfoVOHj = new NlsApplyInfoVO();
        nlsApplyInfoVOHj.setApplySeq(nlsApplyInfoVO.getApplySeq());
        nlsApplyInfoVOHj = nlsApplyInfoService.queryByPk(nlsApplyInfoVO);
        return yedHjLoanReleaseService.applyPsdLoanRelease(reqLoanReleaseBean, nlsApplyInfoVOHj);

    }

    /**
     * 插入一条借据信息: <br>
     * <p>
     * 0.1:caoxin:2019/5/22 17:08: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/5/22 17:08
     * @version 0.1
     * @since 2019/5/22 17:08
     */
    @Deprecated
    private void insertOrUpdateAccLoan(NlsApplyInfoVO nlsApplyInfoVO, String distrNo, String loanNo) throws OcmSystemException {
        int result = 0;
        // 插入一条借据信息
        AccLoanVO accLoanVO = new AccLoanVO();
        // 设置台账表
        accLoanVO.setBillNo(nlsApplyInfoVO.getApplySeq());
        // 设置用信申请流水号
        accLoanVO.setApplySeq(nlsApplyInfoVO.getApplySeq());
        // 设置发放号
        accLoanVO.setDistrNo(distrNo);//成功后需要改回distrNo
        // 设置贷款号
        accLoanVO.setLoanSeq(loanNo);//成功后需要改回loanNo
        // 插入数据
        try {
            result = accLoanService.insertOrUpdateByPk(accLoanVO);
            if (result != 1) {
                throw new OcmSystemException("【放款插槽执行失败】 生成借据失败!!!");
            }
        } catch (Exception e) {
            throw new OcmSystemException("【放款插槽执行失败】 生成借据失败!!!");
        }
    }

    public void updateLmtTerm(NlsApplyInfoVO nlsApplyInfoVO) {
        /*List<NlsApplyInfoVO> nlsApplyInfoVOS = nlsApplyInfoService.queryNlsApplyInfoByDnstsAndState(nlsApplyInfoVO);
        if (Objects.isNull(nlsApplyInfoVOS) || nlsApplyInfoVOS.size() == 0) {
            try {
                // 更新授信有效期为1年
                LmtPrdContVO lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(nlsApplyInfoVO.getLmtApplySeq());
                if (Objects.nonNull(lmtPrdContVO)) {
                    lmtPrdContVO.setExpireDate(TimeUtil.addMonth(lmtPrdContVO.getSignDate(), 12));
                    lmtPrdContService.updateByPk(lmtPrdContVO);
                }
            } catch (Exception e) {
                logger.error("用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】更新额度有效期为1年失败");
                e.printStackTrace();
            }
        }*/
    }

    /**
     * 通过系统ID获取对应pub_sys_info中的营业日期: <br>
     * <p>
     * 0.1:caoxin:2019/4/25 15:25: TODO: <br>
     *
     * @return
     * @author caoxin
     * @date 2019/4/25 15:25
     * @version 0.1
     * @since 2019/4/25 15:25
     */

//    private String getPubSysInfoOpenDay(String sysId) {
//        // 营业日期
//        String openday = pubSysInfoService.getOpenday(sysId);
//        String isOpenday = Optional.ofNullable(openday).orElse("");
//        if (StringUtils.isEmpty(isOpenday)) {
//            logger.info("营业日期获取为空 返回空字符窜", msgTemplate);
//        }
//        return isOpenday;
//    }


    /**
     * 贷款开立服务查询接口
     */
    @Autowired
    @Qualifier("loanRepayResultQryService")
    private LoanRepayResultQryService loanRepayResultQryService;

    /**
     * 合同服务
     */
    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    /**
     * 用信申请服务
     */
    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;

    /**
     * 额度信息服务
     */
    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    /**
     * 贷款开立发放接口服务
     */
    @Autowired
    @Qualifier("yedHjLoanReleaseService")
    private YedHjLoanReleaseService yedHjLoanReleaseService;

    /**
     * 台账信息表
     */
    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;


    @Autowired
    @Qualifier("updateLmtPrdContService")
    private UpdateLmtPrdContService updateLmtPrdContService;

    @Autowired
    @Qualifier("nlsPublicService")
    private NlsPublicService nlsPublicService;
    /**
     * 同步任务
     */
    @Autowired
    @Qualifier("yedSyncLoanInfoService")
    private YedSyncLoanInfoServiceImpl yedSyncLoanInfoService;

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    @Qualifier("nlsQueueSoltComnService")
    private NlsQueueSoltComnService nlsQueueSoltComnService;

    @Autowired
    private CusReferrerInfoService cusReferrerInfoService;
    @Autowired
    private YedGjjLoanService yedGjjLoanService;


    /**
     * 查询推荐人工号表获取出账机构
     * @param
     * @return
     */
    public String getRefferOrgId(NlsCreditInfoVO nlsCreditInfoVO) throws OcmSystemException{
        CusReferrerInfoVO cusReferrerInfoVO = new CusReferrerInfoVO();
        cusReferrerInfoVO.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        cusReferrerInfoVO = cusReferrerInfoService.queryChargeoffBrIdByPk(cusReferrerInfoVO);

        if (Objects.isNull(cusReferrerInfoVO)) {
            throw new OcmSystemException("通过授信申请流水号【" + nlsCreditInfoVO.getLmtApplySeq() + "】，获取到推荐人信息为空！");
        }

        return cusReferrerInfoVO.getChargeOffBrId();
    }
}
